package fr.enseirb.mycub.db;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DBAdapter {
	
	//nom de la db
	protected static final String DATABASE_NAME = "mycub.db";

	// ref pour les erreurs

	public static final int JSON_ERROR = -2;
	public static final int DB_ERROR = -3;
	protected static final int DATABASE_VERSION = 1;

	protected MyCubDBOpenHelper mDbHelper;
	protected SQLiteDatabase mDb;
	protected static DBAdapter mInstance = null;


	public SQLiteDatabase getDB(){
	return mDb;	
	}
	
	protected DBAdapter(Context context) {
		// mContext = context;
		mDbHelper = new MyCubDBOpenHelper(context, DATABASE_NAME, null,DATABASE_VERSION);
		this.open();
	}

	public static synchronized DBAdapter getInstance(Context context) {
		if (mInstance == null)
			mInstance = new DBAdapter(context);
		return mInstance;
	}

	public void close() {
		mDb.close();
	}

	public void open() throws SQLiteException {
		try {
			mDb = mDbHelper.getWritableDatabase();
		} catch (SQLiteException ex) {
			mDb = mDbHelper.getReadableDatabase();
		}
	}

	protected static class MyCubDBOpenHelper extends SQLiteOpenHelper {
		public MyCubDBOpenHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			//bike
			db.execSQL(BikeDBConstants.CREATE_BIKE_STATIONS_TABLE);
			//tram
			db.execSQL(TramwayDBConstants.CREATE_STATIONS_TABLE);
			db.execSQL(TramwayDBConstants.CREATE_LINE_TABLE);
			db.execSQL(TramwayDBConstants.CREATE_SPECIFIC_LINE_TABLE);
			db.execSQL(TramwayDBConstants.CREATE_LINK_LINE_STATION);
			//bus
			db.execSQL(BusDBConstants.CREATE_STATIONS_TABLE);
			db.execSQL(BusDBConstants.CREATE_LINE_TABLE);
			db.execSQL(BusDBConstants.CREATE_SPECIFIC_LINE_TABLE);
			db.execSQL(BusDBConstants.CREATE_LINK_LINE_STATION);
			//parking
			db.execSQL(ParkingDBConstants.CREATE_FREE_PARKING_TABLE);
			db.execSQL(InternetDBConstants.CREATE_INTERNET_TABLE);
		}
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// DO NOT use any constants in DB upgrade, need to put in static
			// older tables structures
		}
	}

}
